package me.bulb.conditional;

import java.util.HashSet;
import java.util.Set;

/**
 * 多条件
 * 
 * @author lijinting01
 * @param <E>
 *
 */
public class MultiCondition<E> implements Condition<E> {

	private Set<Condition<E>> conditions;

	/**
	 * 
	 */
	public MultiCondition() {
		this.conditions = new HashSet<>();
	}

	/**
	 * @param builder
	 */
	private MultiCondition(MultiConditionBuilder<E> builder) {
		this.conditions = builder.conditions;
	}

	public static final <T> MultiConditionBuilder<T> builder(Class<T> c) {
		return new MultiConditionBuilder<>();
	}

	/**
	 * @param condition
	 * @return
	 */
	public MultiCondition<E> add(Condition<E> condition) {
		if (condition != null)
			conditions.add(condition);
		return this;
	}

	@Override
	public boolean apply(E e) {
		for (Condition<E> c : conditions) {
			if (c != null && !c.apply(e)) // 只要有一个不通过就false
				return false;
		}
		return true;
	}

	/**
	 * @author lijinting01
	 *
	 * @param <E>
	 */
	public static class MultiConditionBuilder<E> {
		private Set<Condition<E>> conditions = new HashSet<>();

		public MultiConditionBuilder<E> withCondition(Condition<E> condition) {
			if (condition != null) {
				this.conditions.add(condition);
			}
			return this;
		}

		public MultiCondition<E> build() {
			return new MultiCondition<>(this);
		}
	}

}
